/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * 
 * @version $Id: IniReader.java,v 1.4 2006/03/01 09:52:04 ggardner Exp $
 * @author <a href="mailto:ggardner@macquarie.com"><Grant Gardner></a>
 */
public class IniReader {

    public class KeyMap extends HashMap<String, List<String>> {

        private static final long serialVersionUID = 1L;

        public void add(String key, String value) {

            List<String> list = get(key);
            if (list == null) {
                list = new ArrayList<String>();
                put(key, list);
            }
            list.add(value);

        }
    };

    private final BufferedReader bufferedReader;
    private String currentLine = null;
    private int lineNo = 0;

    public IniReader(BufferedReader reader) {

        bufferedReader = reader;
    }

    public IniReader(File iniFile) throws FileNotFoundException {

        this(new BufferedReader(new FileReader(iniFile)));
    }

    public IniSection readSection() throws INIFormatException, IOException {

        if (atEndOfFile()) {
            return null;
        }
        String sectionName = readSectionName();
        KeyMap keyMap = readKeyMap();

        IniSection section = new IniSection(sectionName, keyMap);
        return section;
    }

    /**
     * @return
     */
    private KeyMap readKeyMap() throws IOException, INIFormatException {

        KeyMap keyMap = new KeyMap();
        while (!atSectionBoundary()) {
            readNextKey(keyMap);
        }
        return keyMap;
    }

    /**
     * @param keyMap
     */
    private void readNextKey(KeyMap keyMap) throws IOException, INIFormatException {

        String line = getCurrentLine();
        int split = line.indexOf('=');
        String key = line.substring(0, split);
        if (line.charAt(split + 1) == '"') {
            keyMap.add(key, readQuotedValue(line.substring(split + 2)));
        } else {
            keyMap.add(key, line.substring(split + 1));
            resetLine();
        }

    }

    /**
     * @param string
     * @return
     */
    private String readQuotedValue(String line) throws INIFormatException, IOException {

        boolean done = false;
        int initalLineNo = lineNo;
        StringBuffer value = new StringBuffer(line.length());
        while (!done) {
            int pos = line.indexOf('"');

            while (pos >= 0 && !done) {
                pos++;
                if (pos == line.length()) {
                    // quote appears at end of line. We're done.
                    value.append(line.substring(0, line.length() - 1));
                    done = true;
                } else if (line.charAt(pos) == '"') {
                    // quoted quote found. Keep going
                    pos++;
                } else {
                    throw new INIFormatException(formatException("Lone quote not at and of line"));
                }
                pos = line.indexOf('"', pos);
            }
            resetLine();

            if (!done) {
                if (atEndOfFile()) {
                    throw new INIFormatException("Quoted value on line " + initalLineNo + " not completed before end of file");
                }
                // Whole line is part of the value, including newline.
                value.append(line);
                value.append("\r\n");

                line = getCurrentLine();
            }

        }

        return value.toString();
    }

    private boolean atEndOfFile() throws IOException {

        return (getCurrentLine() == null);
    }

    private String readSectionName() throws INIFormatException, IOException {

        if (!atSectionBoundary()) {
            throw new INIFormatException(formatException("Expecting section boundary"));
        }

        String line = getCurrentLine();

        int left = line.indexOf('[');
        int right = line.indexOf(']');
        if (!(right > left)) {
            throw new INIFormatException(formatException("Invalid section line"));
        }
        String sectionName = line.substring(left + 1, right - left);
        resetLine();
        return sectionName;
    }

    private void resetLine() {

        currentLine = null;

    }

    private String formatException(String msg) {

        return msg + " at line" + lineNo + ": " + currentLine;
    }

    private boolean atSectionBoundary() throws IOException {

        return (atEndOfFile() || getCurrentLine().charAt(0) == '[');
    }

    private String getCurrentLine() throws IOException {

        if (currentLine == null) {
            currentLine = bufferedReader.readLine();
            if (currentLine != null) {
                lineNo++;
            }

            // Skip blank lines and comments.
            if (currentLine != null && (currentLine.matches("^\\s*$") || currentLine.matches("^\\s*#.*$"))) {
                resetLine();
                getCurrentLine();
            }
        }
        return currentLine;
    }

    public Map<String, IniSection> readAllSections() throws INIFormatException, IOException {

        Map<String, IniSection> sectionList = new HashMap<String, IniSection>();
        while (!atEndOfFile()) {
            IniSection readSection = readSection();
            sectionList.put(readSection.getName(), readSection);
        }
        return sectionList;
    }

}
